import { ref } from 'vue'
import { uploadTextApi, uploadFileApi, getTextUploadsApi, deleteTextUploadApi } from '../api/upload'

// 定义上传项类型
interface TextItem {
  id: number;
  content: string;
  create_at: string;
  user_id: number;
  group_id: number;
}

// 文本上传钩子
export function useTextUpload() {
  const textContent = ref('')
  const shareLink = ref('')
  const isUploading = ref(false)
  const error = ref<Error | null>(null)
  const uploadList = ref<TextItem[]>([])
  const isLoading = ref(false)

  // 删除本地存储相关代码
  // 初始化时从API加载数据
  const initUploadList = async () => {
    isLoading.value = true
    try {
      const response = await getTextUploadsApi()
      uploadList.value = JSON.parse(response)
    } catch (err) {
      error.value = err as Error
      console.error('获取上传列表失败:', err)
    } finally {
      isLoading.value = false
    }
  }

  // 调用初始化函数
  initUploadList()

  // 删除saveUploadList函数

  const uploadText = async () => {
    if (!textContent.value.trim()) {
      alert('请输入文本内容')
      return
    }

    isUploading.value = true
    error.value = null

    try {
      const response = await uploadTextApi(textContent.value)
      shareLink.value = response.data?.shareLink || `http://localhost:5173/share/text/${Date.now()}`

      // 上传成功后刷新列表
      await initUploadList()

      alert('上传成功！')
    } catch (err) {
      error.value = err as Error
      alert('上传失败，请重试')
    } finally {
      isUploading.value = false
    }
  }

  const copyLink = () => {
    navigator.clipboard.writeText(shareLink.value)
    alert('链接已复制到剪贴板')
  }

  // 获取上传列表
  const getUploadList = async () => {
    await initUploadList()
    return uploadList.value
  }

  // 删除当前上传的文本
  const deleteText = async () => {
    if (!shareLink.value) {
      alert('没有可删除的上传内容')
      return
    }

    // 查找当前链接对应的ID
    const currentItem = uploadList.value.find(item => item.content === shareLink.value)
    if (!currentItem) {
      alert('未找到对应的上传内容')
      return
    }

    try {
      await deleteTextUploadApi(currentItem.id)
      shareLink.value = ''
      // 删除成功后刷新列表
      await initUploadList()
      alert('删除成功')
    } catch (err) {
      error.value = err as Error
      alert('删除失败，请重试')
    }
  }

  // 删除指定的上传项
  const deleteSpecificUpload = async (id: number) => {
    try {
      await deleteTextUploadApi(id)
      // 删除成功后刷新列表
      await initUploadList()
      alert('删除成功')
    } catch (err) {
      error.value = err as Error
      alert('删除失败，请重试')
    }
  }

  return {
    textContent,
    shareLink,
    isUploading,
    isLoading,
    error,
    uploadList,
    uploadText,
    copyLink,
    getUploadList,
    deleteUpload: deleteText,
    deleteSpecificUpload
  }
}

// 文件上传钩子
export function useFileUpload() {
  const selectedFile = ref<File | null>(null)
  const shareLink = ref('')
  const isUploading = ref(false)
  const error = ref<Error | null>(null)
  const progress = ref(0)

  const handleFileChange = (event: Event) => {
    const target = event.target as HTMLInputElement
    if (target.files && target.files.length > 0) {
      selectedFile.value = target.files[0]
    }
  }

  const handleDrop = (event: DragEvent) => {
    event.preventDefault()
    if (event.dataTransfer && event.dataTransfer.files.length > 0) {
      selectedFile.value = event.dataTransfer.files[0]
    }
  }

  const formatFileSize = (size: number): string => {
    if (size < 1024) return size + ' B'
    else if (size < 1048576) return (size / 1024).toFixed(2) + ' KB'
    else return (size / 1048576).toFixed(2) + ' MB'
  }

  const uploadFile = async () => {
    if (!selectedFile.value) {
      alert('请选择文件')
      return
    }

    isUploading.value = true
    error.value = null
    progress.value = 0

    // 模拟上传进度
    const interval = setInterval(() => {
      progress.value += 5
      if (progress.value >= 100) {
        clearInterval(interval)
      }
    }, 200)

    try {
      const response = await uploadFileApi(selectedFile.value)
      // 使用mock返回的分享链接
      shareLink.value = response.data?.shareLink || `http://localhost:5173/share/file/${Date.now()}`
      alert('上传成功！')
    } catch (err) {
      error.value = err as Error
      alert('上传失败，请重试')
    } finally {
      clearInterval(interval)
      progress.value = 100
      isUploading.value = false
    }
  }

  const copyLink = () => {
    navigator.clipboard.writeText(shareLink.value)
    alert('链接已复制到剪贴板')
  }

  return {
    selectedFile,
    shareLink,
    isUploading,
    error,
    progress,
    handleFileChange,
    handleDrop,
    formatFileSize,
    uploadFile,
    copyLink
  }
}